<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" :content="$t('设置')" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <div class="l-rblock" style="padding-bottom: 32px">
          <div class="l-rblock" style="overflow: hidden auto">
            <el-tree
              v-loading="treeLoading"
              :data="treeShowData"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <span class="lr-tree-node" slot-scope="{ node }">
                <i class="el-icon-notebook-2"></i>
                {{ node.label }}
              </span>
            </el-tree>
          </div>
          <div class="l-bottom">
            <el-input
              :placeholder="$t('请输入名称')"
              @keyup.enter.native="hanleSearchCategory"
              v-model="searchCategoryWord"
              size="mini"
            >
              <el-button
                @click="hanleSearchCategory"
                slot="append"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </div>
        </div>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入名称')"
            @keyup.enter.native="hanleSearch"
            v-model="keyWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()" :btnText="$t('新增')"></l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="columns"
        :dataSource="tableData"
        row-key="F_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <l-table-btns
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>
    <!-- 编辑/新增组件 -->
    <l-dialog
      :width="900"
      :height="750"
      :visible.sync="formVisible"
      :title="formTitle"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <visual-form ref="form" :categoryData="treeData"></visual-form>
    </l-dialog>
    <!-- 预览组件 -->
    <l-dialog
      :width="780"
      :height="500"
      :visible.sync="componentVisible"
      :title="$t('预览组件')"
      :hasBtns="false"
    >
      <div style="overflow: hidden auto; height: 100%;padding:20px;box-sizing: border-box;">
        <avue-echart-vue
          :option="vueOption"
          width="100%"
          height="100%"
        ></avue-echart-vue>
      </div>
    </l-dialog>
    <!-- 分类管理 -->
    <l-drawer
      :title="$t('分类管理')"
      :visible.sync="categoryVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <l-dataitem-index classifyCode="ComponentType"></l-dataitem-index>
    </l-drawer>
  </l-layout>
</template>

<script>
import AvueEchartVue from "../../components/vue";
import visualForm from "./form";
const api = window.$api.vdata.component;
export default {
  components: {
    visualForm,
    AvueEchartVue,
  },
  props: {
    menu: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      treeLoading: false,
      treeData: [],
      treeShowData: [],
      vueOption: {},
      tableData: [],
      formEdit: false,
      formEditRow: null,
      keyWord: "",
      tableLoading: false,
      tableTotal: 0,
      tableCurrentPage: 1,
      // 表格
      columns: [
        { label: "组件编码", prop: "f_Code", minWidth: "150" },
        { label: "组件名称", prop: "f_Name", minWidth: "150" },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑",width:60 },
        { prop: "Delete", label: "删除",width:60 },
        { prop: "ShowDrawer", label: "预览",width:60 },
      ],
      option: {
        tip: false,
        header: true,
        menu: true,
        selection: true,
        dialogWidth: "70%",
        labelWidth: 100,
        index: true,
        align: "center",
        headerAlign: "center",
        column: [
          {
            label: "组件名称",
            prop: "name",
            row: true,
            rules: [
              {
                required: true,
                message: "请输入组件名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "组件数据",
            prop: "content",
            span: 24,
            hide: true,
          },
          {
            label: "组件预览",
            prop: "view",
            span: 24,
            hide: true,
          },
        ],
      },
      preVisible: false,
      categoryVisible: false,
      categoryId: "",
      searchCategoryWord: "",
      formVisible: false,
      formTitle: "",
      tablePageSize: 50,
      componentVisible: false,
    };
  },
  created() {
    this.loadTablePageData();
  },
  mounted() {
    this.lr_loadDataItem("ComponentType");
  },
  watch: {
    dataItemTree_Function: {
      handler(n) {
        this.treeData = n;
        this.treeShowData = n;
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    dataItemTree_Function() {
      return this.lr_dataItemTree(this.lr_dataItem["ComponentType"]);
    },
  },
  methods: {
    refreshCategory(data) {
      this.searchCategoryWord = "";
      this.treeData = [];
      data.forEach((item) => {
        this.treeData.push({ value: item.value, label: item.label });
      });
      this.treeShowData = this.treeData;
    },
    hanleSearch() {
      this.loadTablePageData();
    },
    loadTablePageData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        // sidx:'F_CreateDate DESC',
        f_Type: this.categoryId,
        keyword: this.keyWord,
      };
      api
        .getPage(queryData)
        .then((res) => {
          const tableData = this.$deepClone(res.data.data);
          this.tableData = tableData.rows;
          this.tableTotal = tableData.records;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    handleAdd() {
      this.formEdit = false;
      this.showForm("新增");
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePageData(true);
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.showForm("编辑");
    },
    handleDelete($index, row) {
      this.$confirm(this.$t("此操作将永久删除该数据, 是否继续?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      }).then(() => {
        api
          .delObj(row.f_Id)
          .then(() => {
            this.$message({
              type: "success",
              message: this.$t("删除成功!"),
            });
            this.loadTablePageData();
          })
          .catch(() => {});
      });
    },
    handleSettingClick() {
      this.categoryVisible = true;
    },
    handleNodeClick(data) {
      this.categoryId = data.value;
      this.loadTablePageData();
    },
    hanleSearchCategory() {
      if (this.searchCategoryWord) {
        this.treeShowData = this.treeData.filter(
          (item) => item.label.indexOf(this.searchCategoryWord) > -1
        );
      } else {
        this.treeShowData = this.treeData;
      }
    },
    showForm(text) {
      this.loadCategory();
      this.formTitle = text;
      this.formVisible = true;
    },
    loadCategory() {
      this.treeData = [];
      this.lr_dataItemTree(this.lr_dataItem["ComponentType"]).forEach(
        (item) => {
          this.treeData.push({ value: item.value, label: item.label });
        }
      );
    },
    async handleSave(showLoading, hideLoading) {
      showLoading('保存数据中...')
                if (await this.$refs.form.validateForm()) {
                    const res = await this.$refs.form.saveForm({ keyValue: this.formEdit? this.formEditRow.f_Id :'', isEdit: this.formEdit })
                    if (res) {
                        const msg = this.formEdit ? this.$t('更新成功!') : this.$t('新增成功!')
                        this.$message({
                            type: 'success',
                            message: this.$t(msg)
                        })
                        this.loadTablePageData()
                        this.formVisible = false
                    }
                }
                hideLoading()
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.$refs.form.loadFormData({ keyValue: this.formEditRow.f_Id });
        hideLoading();
      }
    },
    handleShowDrawer($index, row) {
      this.$set(this.vueOption, 'f_Content', row.lrDatavComponentdetail_F_Component)
      this.componentVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.components {
  &_content {
    display: flex;
    align-items: flex-end;
    flex-direction: column;
  }

  &_left,
  &_right {
    width: 100%;
  }
}
</style>